"use client"

import { useState, useEffect, useRef, useCallback } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Input } from "@/components/ui/input"
import { TrendingUp, TrendingDown, Activity, RefreshCw, BarChart3, Eye, AlertCircle, Play, Square, ArrowUpDown, ArrowUp, ArrowDown, Search, X, Star, Plus, Target } from "lucide-react"
import { getRecommendations, executeBuyTask, executeSellTask, GetRecommendationsParams } from "@/lib/api/recommendations"
import { useApiCall } from "@/lib/hooks/use-api-call"
import { useWatch } from "@/lib/hooks/use-watch"
import { useAuth } from "@/lib/hooks/use-auth"
import { useToast } from "@/hooks/use-toast"
import { UserNav } from "@/components/user-nav"
import { AuthGuard } from "@/components/auth-guard"
import { ThemeSwitch } from "@/components/theme-switch"
import { StockSearchDialog } from "@/components/stock-search-dialog"
import { StockListView } from "@/components/stock-list-view"
import { AppStockRecommendation as StockCardType } from "@/components/stock-card"

// 使用从 StockCard 组件导入的类型
type AppStockRecommendation = StockCardType

interface ProcessedRecommendationsData {
  date: string
  update_time: string
  daily_stocks: AppStockRecommendation[]        // 今日推荐（strong + weak）
  continuous_monitoring: AppStockRecommendation[] // 持续监控
  statistics: {
    total_stocks: number
    strong_count: number   // 强势股票数量
    weak_count: number     // 弱势股票数量
  }
}

/**
 * 处理API数据，转换为应用内部数据格式
 * 直接使用后端返回的数据和排序，不再前端分类
 */
function processApiData(apiResponse: any): ProcessedRecommendationsData {
  console.log('🔍 处理API数据:', apiResponse)

  // 提取股票列表 - data 字段直接是数组
  const stocks = Array.isArray(apiResponse) ? apiResponse : []
  
  // 打印前10条数据的成交量比，用于调试排序
  console.log('📊 前10条数据的成交量比:', stocks.slice(0, 10).map((s: any) => ({
    name: s.name,
    code: s.code,
    volume: s.volume,
    prevVolume: s.prevVolume,
    ratio: s.prevVolume > 0 ? (s.volume / s.prevVolume * 100).toFixed(0) + '%' : 'N/A',
    type: s.recommendationType
  })))

  // 转换股票数据的通用函数
  const convertStock = (item: any): AppStockRecommendation => ({
    code: item.code,
    name: item.name || item.code,  // 如果 name 为空，使用 code
    change_percent: item.changePercent,
    volume: item.volume,
    prev_volume: item.prevVolume,
    energy_value: item.energyValue,
    holding_days: item.holdingDays,
    reason: item.reason || '系统推荐',
    strength: item.score,  // 强度评分
    recommendationType: item.recommendationType,  // 保留类型标识
  })

  // 按类型分组（保持后端返回的原始顺序）
  const dailyStocks = stocks
    .filter((s: any) => s.recommendationType === 'strong' || s.recommendationType === 'weak')
    .map(convertStock)
  
  const monitoringStocks = stocks
    .filter((s: any) => s.recommendationType === 'monitoring')
    .map(convertStock)

  // 统计数据
  const strongCount = stocks.filter((s: any) => s.recommendationType === 'strong').length
  const weakCount = stocks.filter((s: any) => s.recommendationType === 'weak').length

  console.log('📊 数据统计:', {
    daily: dailyStocks.length,
    monitoring: monitoringStocks.length,
    strong: strongCount,
    weak: weakCount,
    total: stocks.length
  })

  return {
    date: new Date().toISOString().split('T')[0],
    update_time: new Date().toLocaleString('zh-CN'),
    daily_stocks: dailyStocks,
    continuous_monitoring: monitoringStocks,
    statistics: {
      total_stocks: stocks.length,
      strong_count: strongCount,
      weak_count: weakCount,
    },
  }
}

export default function StockDashboard() {
  const router = useRouter()
  const [data, setData] = useState<ProcessedRecommendationsData | null>(null)
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null)
  const [mounted, setMounted] = useState(false)
  const [buyLoading, setBuyLoading] = useState(false)
  const [sellLoading, setSellLoading] = useState(false)
  // 计算默认日期：如果当前时间在9:30之前，使用前一天的日期
  const getDefaultDate = () => {
    const now = new Date()
    const currentHour = now.getHours()
    const currentMinute = now.getMinutes()

    // 如果当前时间在9:30之前，使用前一天
    if (currentHour < 9 || (currentHour === 9 && currentMinute < 30)) {
      const yesterday = new Date(now)
      yesterday.setDate(yesterday.getDate() - 1)
      return yesterday.toISOString().split('T')[0]
    }

    return now.toISOString().split('T')[0]
  }

  const selectedDate = getDefaultDate()
  const [activeTab, setActiveTab] = useState<'all-stocks' | 'key-focus' | 'my-watchlist'>('all-stocks')
  const [sortBy, setSortBy] = useState<'energy_value' | 'strength' | 'volume' | 'change_percent' | 'volume_ratio'>('energy_value')
  const [sortOrder, setSortOrder] = useState<'desc' | 'asc'>('desc')
  const [filterCodes, setFilterCodes] = useState<string>('')
  const [isAutoRefreshing, setIsAutoRefreshing] = useState(false)
  const [consecutiveErrors, setConsecutiveErrors] = useState(0)
  const { toast } = useToast()
  const { isAuthenticated, userInfo } = useAuth()
  const watchHook = useWatch()

  // 使用ref存储最新的状态值，确保定时器能获取到最新状态
  const activeTabRef = useRef(activeTab)
  const isRefreshingRef = useRef(false)  // 跟踪是否正在刷新
  const timeoutIdRef = useRef<NodeJS.Timeout | null>(null)  // 存储定时器ID
  const consecutiveErrorsRef = useRef(consecutiveErrors)  // 存储最新的错误计数
  
  // 每次activeTab变化时，更新ref并打印日志
  useEffect(() => {
    console.log(`📌 activeTab变化: ${activeTab}`)
    activeTabRef.current = activeTab
    console.log(`📌 activeTabRef.current更新为: ${activeTabRef.current}`)
  }, [activeTab])
  
  // 每次consecutiveErrors变化时，更新ref
  useEffect(() => {
    consecutiveErrorsRef.current = consecutiveErrors
  }, [consecutiveErrors])

  // 判断是否为admin用户
  const isAdmin = userInfo?.username === 'admin'

  // 移除自动刷新，只在用户主动点击时刷新

  // 使用API调用Hook
  const {
    execute: fetchRecommendations,
    isLoading
  } = useApiCall(getRecommendations, {
    showToast: false, // 我们手动处理Toast
    autoRetry: true,
    retryCount: 3
  })

  // 客户端挂载检测
  useEffect(() => {
    setMounted(true)
    setLastUpdate(new Date())
  }, [])

  // 初始化加载关注列表（仅在已登录时）
  useEffect(() => {
    if (mounted && isAuthenticated) {
      console.log('页面初始化，加载关注列表')
      watchHook.refreshWatchlist()
    }
  }, [mounted, isAuthenticated])

  // 初次加载数据 - 并行加载所有标签页的数据
  useEffect(() => {
    const loadAllData = async () => {
      if (!mounted) return

      const getSortByParam = () => {
        switch (sortBy) {
          case 'energy_value': return 'energy'      // 能量值
          case 'strength': return 'score'            // 强度/评分
          case 'volume': return 'volume'             // 成交量
          case 'change_percent': return 'change'     // 涨跌幅
          case 'volume_ratio': return 'volume_ratio' // 成交量比
          default: return sortBy
        }
      }

      try {
        // 初次加载时，并行获取今日推荐和持续监控
        const [dailyResponse, monitoringResponse] = await Promise.all([
          fetchRecommendations({
            target_date: selectedDate,
            filter: 'daily',
            sort_by: getSortByParam(),
            sort_order: sortOrder
          }),
          fetchRecommendations({
            target_date: selectedDate,
            filter: 'monitoring',
            sort_by: getSortByParam(),
            sort_order: sortOrder
          })
        ])

        const dailyStocks = Array.isArray(dailyResponse) ? dailyResponse : []
        const monitoringStocks = Array.isArray(monitoringResponse) ? monitoringResponse : []
        const allStocks = [...dailyStocks, ...monitoringStocks]

        const processedData = processApiData(allStocks)
        setData(processedData)
        setLastUpdate(new Date())

        toast({
          title: "数据加载成功",
          description: `获取到 ${selectedDate} 的推荐数据`,
          duration: 3000,
        })
      } catch (error) {
        console.error('初次加载数据失败:', error)
      }
    }

    loadAllData()
  }, [mounted])

  // 当用户修改排序时，重新加载当前标签页的数据
  useEffect(() => {
    if (mounted && data) {
      loadData(false, undefined, false, sortBy, sortOrder) // 传递最新的排序参数
    }
  }, [sortBy, sortOrder])

  // 设置串行自动刷新 (带退避策略) - 使用ref确保只有一个定时器实例
  useEffect(() => {
    // 清理旧的定时器，确保只有一个定时器实例
    const clearTimer = () => {
      if (timeoutIdRef.current) {
        clearTimeout(timeoutIdRef.current)
        timeoutIdRef.current = null
      }
    }

    const scheduleNextRefresh = () => {
      // 先清理可能存在的旧定时器
      clearTimer()
      
      // 使用ref获取最新的错误计数
      const delay = getBackoffDelay(consecutiveErrorsRef.current)
      console.log(`⏰ 安排下次刷新，延迟 ${delay / 1000} 秒`)

      timeoutIdRef.current = setTimeout(async () => {
        // 防止重复执行：检查是否已经有刷新在进行中
        if (isRefreshingRef.current) {
          console.log('⚠️ 已有刷新任务在执行，跳过本次')
          scheduleNextRefresh()
          return
        }

        isRefreshingRef.current = true
        setIsAutoRefreshing(true)
        
        try {
          // 使用ref获取最新的activeTab值，确保定时器刷新正确的标签页数据
          const currentTab = activeTabRef.current
          console.log(`🔄 自动刷新开始 - 当前标签页: ${currentTab}, 时间: ${new Date().toLocaleTimeString()}`)
          await loadData(false, selectedDate, true, undefined, undefined, currentTab) // 无感刷新：不显示Toast
          console.log('✅ 自动刷新成功，重置错误计数')
          setConsecutiveErrors(0) // 成功时重置错误计数
        } catch (error) {
          const newErrorCount = consecutiveErrorsRef.current + 1
          console.error(`❌ 自动刷新失败 (第${newErrorCount}次):`, error)
          setConsecutiveErrors(newErrorCount)
        } finally {
          isRefreshingRef.current = false
          setIsAutoRefreshing(false)
          // 等待当前请求完成后，安排下一次刷新（15秒后）
          scheduleNextRefresh()
        }
      }, delay)
    }

    // 初始化时启动定时器 (首次加载完成后)
    // 只依赖mounted和data的初始化状态，避免频繁重建定时器
    if (mounted && data && !timeoutIdRef.current) {
      console.log('🚀 初始化自动刷新定时器')
      scheduleNextRefresh()
    }

    return () => {
      console.log('🧹 清理定时器')
      clearTimer()
    }
    // 最小化依赖：只在mounted或data初始化时启动定时器
  }, [mounted, data])

  const loadData = async (
    showToast = true, 
    date?: string, 
    isAutoRefresh = false,
    customSortBy?: typeof sortBy,
    customSortOrder?: typeof sortOrder,
    customActiveTab?: typeof activeTab  // 新增：支持传入指定的标签页
  ) => {
    const queryDate = date || selectedDate
    const currentSortBy = customSortBy || sortBy
    const currentSortOrder = customSortOrder || sortOrder
    // 关键修复：使用activeTabRef.current而不是activeTab，确保获取最新值
    const currentActiveTab = customActiveTab || activeTabRef.current
    
    console.log(`🔍 loadData调用 - customActiveTab: ${customActiveTab}, activeTabRef.current: ${activeTabRef.current}, currentActiveTab: ${currentActiveTab}`)

    // 将前端字段映射为后端API支持的字段
    const getSortByParam = () => {
      switch (currentSortBy) {
        case 'energy_value': return 'energy'      // 能量值
        case 'strength': return 'score'            // 强度/评分
        case 'volume': return 'volume'             // 成交量
        case 'change_percent': return 'change'     // 涨跌幅
        case 'volume_ratio': return 'volume_ratio' // 成交量比
        default: return currentSortBy
      }
    }

    try {
      // 根据当前激活的标签页，只加载对应的数据
      if (currentActiveTab === 'my-watchlist') {
        // 我的关注标签：刷新关注列表
        watchHook.refreshWatchlist()
        setLastUpdate(new Date())
        return  // 直接返回，不需要更新推荐数据
      }

      // 只加载当前标签页对应的数据
      const filter = currentActiveTab === 'all-stocks' ? 'daily' : 'monitoring'
      const sortByParam = getSortByParam()
      
      console.log('📡 API请求参数:', {
        sortBy前端: currentSortBy,
        sortBy后端: sortByParam,
        sortOrder: currentSortOrder,
        filter
      })
      
      const response = await fetchRecommendations({
        target_date: queryDate,
        filter,
        sort_by: sortByParam,
        sort_order: currentSortOrder
      })

      if (!response) return

      const stocks = Array.isArray(response) ? response : []

      // 根据当前标签页，更新对应的数据
      let updatedData: ProcessedRecommendationsData
      const processedStocks = processApiData(stocks)

      if (!data) {
        // 如果是第一次加载（data为null），直接使用处理后的数据
        updatedData = processedStocks
      } else if (currentActiveTab === 'all-stocks') {
        // 更新今日推荐数据
        updatedData = {
          ...data,
          daily_stocks: processedStocks.daily_stocks,
          date: processedStocks.date,
          update_time: processedStocks.update_time,
          statistics: {
            total_stocks: processedStocks.statistics.total_stocks + data.continuous_monitoring.length,
            strong_count: processedStocks.statistics.strong_count,
            weak_count: processedStocks.statistics.weak_count,
          }
        }
      } else {
        // 更新持续监控数据
        updatedData = {
          ...data,
          continuous_monitoring: processedStocks.continuous_monitoring,
          date: processedStocks.date,
          update_time: processedStocks.update_time,
          statistics: {
            total_stocks: data.daily_stocks.length + processedStocks.continuous_monitoring.length,
            strong_count: data.statistics.strong_count,
            weak_count: data.statistics.weak_count,
          }
        }
      }

      const processedData = updatedData

      // 检查数据是否有实际变化
      const hasDataChanged = !data ||
        JSON.stringify(data.daily_stocks) !== JSON.stringify(processedData.daily_stocks) ||
        JSON.stringify(data.continuous_monitoring) !== JSON.stringify(processedData.continuous_monitoring)

      setData(processedData)
      setLastUpdate(new Date())

      // 自动刷新时不显示成功Toast，实现无感刷新
      if (showToast && !isAutoRefresh) {
        toast({
          title: "数据更新成功",
          description: `获取到 ${queryDate} 的推荐数据`,
          duration: 3000,
        })
      }

      // 无感刷新时，如果数据有变化，在控制台输出提示
      if (isAutoRefresh && hasDataChanged) {
        console.log('📊 数据已更新 - 检测到股票信息变化')
      }
    } catch (error) {
      console.error('获取推荐数据失败:', error)
      // 自动刷新失败时也不显示Toast，避免打扰用户
      if (showToast && !isAutoRefresh) {
        toast({
          title: "数据更新失败",
          description: "无法获取最新数据，请检查网络连接",
          variant: "destructive",
          duration: 5000,
        })
      }
    }
  }

  const handleRefresh = () => {
    // 手动刷新时重置错误计数
    setConsecutiveErrors(0)
    loadData(true, selectedDate)
  }


  // 计算退避延迟时间 (指数退避)
  const getBackoffDelay = (errorCount: number): number => {
    if (errorCount === 0) return 15000 // 正常情况：15秒

    // 指数退避：15s, 30s, 60s, 120s, 300s (最大5分钟)
    const baseDelay = 15000
    const backoffMultiplier = Math.min(Math.pow(2, errorCount), 20) // 最大20倍
    const delay = baseDelay * backoffMultiplier

    console.log(`🔄 连续错误 ${errorCount} 次，下次刷新延迟 ${delay / 1000} 秒`)
    return delay
  }

  // 前端只做筛选，不再排序（所有排序都由后端完成）
  const sortStocksIfNeeded = (stocks: AppStockRecommendation[]) => {
    // 后端已支持所有字段的排序（包括 volume_ratio），直接返回
    return stocks
  }


  const handleSort = (field: typeof sortBy) => {
    if (sortBy === field) {
      setSortOrder(sortOrder === 'desc' ? 'asc' : 'desc')
    } else {
      setSortBy(field)
      setSortOrder('desc')
    }
  }

  // 筛选股票数据
  const filterStocks = (stocks: AppStockRecommendation[]) => {
    if (!filterCodes.trim()) return stocks

    const codes = filterCodes
      .split(',')
      .map(code => code.trim())
      .filter(code => code.length > 0)

    if (codes.length === 0) return stocks

    return stocks.filter(stock =>
      codes.some(code =>
        stock.code.includes(code) ||
        stock.name.includes(code)
      )
    )
  }

  // 处理股票数据：筛选 + 条件排序（后端已排序，前端只需筛选）
  const processStocks = (stocks: AppStockRecommendation[]) => {
    const filtered = filterStocks(stocks)
    return sortStocksIfNeeded(filtered)  // 仅在必要时前端排序
  }

  // 执行开盘买入任务
  const handleExecuteBuy = async () => {
    setBuyLoading(true)
    try {
      const response = await executeBuyTask()
      toast({
        title: "开盘买入成功",
        description: `任务执行完成，耗时: ${response.data.execution_time}`,
        duration: 3000,
      })
    } catch (error: any) {
      toast({
        variant: "destructive",
        title: "开盘买入失败",
        description: error.message || "执行买入任务时发生错误",
        duration: 3000,
      })
    } finally {
      setBuyLoading(false)
    }
  }

  // 执行收盘卖出任务  
  const handleExecuteSell = async () => {
    setSellLoading(true)
    try {
      const response = await executeSellTask()
      toast({
        title: "收盘卖出成功",
        description: `任务执行完成，耗时: ${response.data.execution_time}`,
        duration: 3000,
      })
    } catch (error: any) {
      toast({
        variant: "destructive",
        title: "收盘卖出失败",
        description: error.message || "执行卖出任务时发生错误",
        duration: 3000,
      })
    } finally {
      setSellLoading(false)
    }
  }

  // 防止水合错误，等待客户端挂载
  if (!mounted) {
    return null
  }

  return (
    <AuthGuard requireAuth={false}>
      <div className="min-h-screen bg-background">
        {/* Header */}
        <header className="border-b bg-card">
          <div className="container mx-auto px-4 py-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-4">
                <BarChart3 className="w-8 h-8 text-accent" />
                <div>
                  <h1 className="text-2xl font-bold text-balance">股票AI智能分析系统</h1>
                  <p className="text-sm text-muted-foreground">实时股票推荐监控平台</p>
                </div>
              </div>

              <div className="flex items-center space-x-4">
                <div className="text-right text-sm">
                  <p className="text-muted-foreground">最后更新</p>
                  <div className="flex items-center gap-2">
                    <p className="font-medium">{lastUpdate ? lastUpdate.toLocaleTimeString("zh-CN") : '--'}</p>
                    {isAutoRefreshing && (
                      <RefreshCw className="w-3 h-3 animate-spin text-accent" />
                    )}
                  </div>
                  <p className="text-xs text-muted-foreground">
                    {isAutoRefreshing ? "更新中..." : "自动刷新"}
                  </p>
                </div>

                {/* 管理员专用按钮 - 只有admin用户可见 */}
                {isAdmin && (
                  <>
                    {/* 开盘买入按钮 */}
                    <Button
                      onClick={handleExecuteBuy}
                      disabled={buyLoading || isLoading}
                      size="sm"
                      className="bg-success hover:bg-success/90 text-white transition-all duration-200 hover:scale-105 active:scale-95 hover:shadow-lg"
                    >
                      <Play className={`w-4 h-4 mr-2 transition-transform ${buyLoading ? "animate-spin" : ""}`} />
                      开盘买入
                    </Button>

                    {/* 收盘卖出按钮 */}
                    <Button
                      onClick={handleExecuteSell}
                      disabled={sellLoading || isLoading}
                      size="sm"
                      className="bg-destructive hover:bg-destructive/90 text-white transition-all duration-200 hover:scale-105 active:scale-95 hover:shadow-lg"
                    >
                      <Square className={`w-4 h-4 mr-2 transition-transform ${sellLoading ? "animate-spin" : ""}`} />
                      收盘卖出
                    </Button>
                  </>
                )}

                {/* 信号分析按钮 */}
                <Button
                  onClick={() => router.push('/signals')}
                  size="sm"
                  variant="outline"
                  className="border-accent text-accent hover:bg-accent/10 transition-all duration-200 hover:scale-105 active:scale-95"
                >
                  <Target className="w-4 h-4 mr-2 transition-transform" />
                  信号分析
                </Button>

                <Button
                  onClick={handleRefresh}
                  disabled={isLoading}
                  size="sm"
                  className="bg-accent hover:bg-accent/90 transition-all duration-200 hover:scale-105 active:scale-95"
                >
                  <RefreshCw className={`w-4 h-4 mr-2 transition-transform ${isLoading ? "animate-spin" : ""}`} />
                  刷新数据
                </Button>

                {/* 主题切换和用户导航 */}
                <div className="flex items-center space-x-2">
                  <ThemeSwitch />
                  <UserNav />
                </div>
              </div>
            </div>
          </div>
        </header>

        <main className="container mx-auto px-4 py-6">
          {/* Statistics Cards */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">总股票数</CardTitle>
                <BarChart3 className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                {data ? (
                  <>
                    <div className="text-2xl font-bold">{data.statistics.total_stocks}</div>
                    <p className="text-xs text-muted-foreground">推荐日期: {data.date}</p>
                  </>
                ) : (
                  <div className="space-y-2">
                    <Skeleton className="h-8 w-16" />
                    <Skeleton className="h-3 w-24" />
                  </div>
                )}
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">强势股票</CardTitle>
                <TrendingUp className="h-4 w-4 text-success" />
              </CardHeader>
              <CardContent>
                {data ? (
                  <>
                    <div className="text-2xl font-bold text-success">{data.statistics.strong_count}</div>
                    <p className="text-xs text-muted-foreground">今日推荐</p>
                  </>
                ) : (
                  <div className="space-y-2">
                    <Skeleton className="h-8 w-16" />
                    <Skeleton className="h-3 w-20" />
                  </div>
                )}
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">弱势股票</CardTitle>
                <TrendingDown className="h-4 w-4 text-destructive" />
              </CardHeader>
              <CardContent>
                {data ? (
                  <>
                    <div className="text-2xl font-bold text-destructive">{data.statistics.weak_count}</div>
                    <p className="text-xs text-muted-foreground">今日推荐</p>
                  </>
                ) : (
                  <div className="space-y-2">
                    <Skeleton className="h-8 w-16" />
                    <Skeleton className="h-3 w-20" />
                  </div>
                )}
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">监控状态</CardTitle>
                <Eye className="h-4 w-4 text-accent" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold flex items-center gap-2">
                  <span className={consecutiveErrors > 0 ? "text-destructive" : "text-accent"}>
                    {consecutiveErrors > 0 ? "异常" : "实时"}
                  </span>
                  {isAutoRefreshing && <RefreshCw className="w-4 h-4 animate-spin" />}
                </div>
                <p className="text-xs text-muted-foreground">
                  {consecutiveErrors > 0 ? (
                    `连续错误 ${consecutiveErrors} 次 • ${getBackoffDelay(consecutiveErrors) / 1000}s 间隔`
                  ) : (
                    "串行刷新 • 15秒间隔"
                  )}
                  {isAutoRefreshing && ' • 刷新中...'}
                </p>
              </CardContent>
            </Card>
          </div>

          {/* Stock Recommendations Tabs */}
          <Tabs
            defaultValue="all-stocks"
            value={activeTab}
            className="w-full"
            onValueChange={(value) => {
              const newTab = value as typeof activeTab
              setActiveTab(newTab)
              console.log(`切换到标签页: ${newTab}`)
              // 切换标签页时立即加载该标签页的最新数据
              loadData(false, selectedDate, false, undefined, undefined, newTab)
            }}
          >
            <TabsList className="grid w-full grid-cols-3">
              <TabsTrigger value="all-stocks" className="flex items-center space-x-2">
                <BarChart3 className="w-4 h-4" />
                <span>今日推荐</span>
                {data && data.daily_stocks.length > 0 && (
                  <Badge variant="secondary" className="ml-1 text-xs">
                    {data.daily_stocks.length}
                  </Badge>
                )}
              </TabsTrigger>
              <TabsTrigger value="my-watchlist" className="flex items-center space-x-2">
                <Star className="w-4 h-4" />
                <span>我的关注</span>
                {watchHook.watchedStocks.length > 0 && (
                  <Badge variant="secondary" className="ml-1 text-xs">
                    {watchHook.watchedStocks.length}
                  </Badge>
                )}
              </TabsTrigger>
              <TabsTrigger value="key-focus" className="flex items-center space-x-2">
                <Eye className="w-4 h-4" />
                <span>重点关注</span>
                {data && data.continuous_monitoring.length > 0 && (
                  <Badge variant="secondary" className="ml-1 text-xs">
                    {data.continuous_monitoring.length}
                  </Badge>
                )}
              </TabsTrigger>
            </TabsList>

            <TabsContent value="all-stocks" className="mt-6">
              <StockListView
                stocks={data ? processStocks(data.daily_stocks) : undefined}
                isLoading={isLoading}
                sortBy={sortBy}
                sortOrder={sortOrder}
                onSort={handleSort}
                filterCodes={filterCodes}
                onFilterChange={setFilterCodes}
                getStockType={(stock) => {
                  // 直接使用后端返回的 recommendationType
                  return stock.recommendationType || "monitoring"
                }}
                watchHook={watchHook}
                emptyState={{
                  icon: BarChart3,
                  title: "暂无股票推荐",
                  description: "系统暂未生成股票推荐，请稍后刷新查看。",
                  actionText: "刷新数据",
                  onAction: handleRefresh
                }}
                skeletonCount={16}
              />
            </TabsContent>

            <TabsContent value="my-watchlist" className="mt-6">
              <StockListView
                stocks={processStocks(watchHook.watchedStockRecommendations)}
                isLoading={watchHook.isFetching}
                sortBy={sortBy}
                sortOrder={sortOrder}
                onSort={handleSort}
                filterCodes={filterCodes}
                onFilterChange={setFilterCodes}
                getStockType={() => "monitoring"}
                watchHook={watchHook}
                showHoldingDays={false}
                extraButton={
                  <StockSearchDialog
                    onStockAdded={() => {
                      // 关注成功后刷新关注列表
                      watchHook.refreshWatchlist()
                    }}
                  >
                    <Button variant="outline" className="flex items-center space-x-2">
                      <Plus className="w-4 h-4" />
                      <span>搜索股票</span>
                    </Button>
                  </StockSearchDialog>
                }
                emptyState={{
                  icon: Star,
                  title: "暂无关注股票",
                  description: "您还没有关注任何股票。点击股票卡片右上角的⭐图标来关注您感兴趣的股票。",
                  actionText: "浏览全部股票",
                  onAction: () => {
                    const tabsList = document.querySelector('[role="tablist"]')
                    const allStocksTab = tabsList?.querySelector('[value="all-stocks"]') as HTMLElement
                    allStocksTab?.click()
                  }
                }}
                skeletonCount={4}
              />
            </TabsContent>

            <TabsContent value="key-focus" className="mt-6">
              <StockListView
                stocks={data ? processStocks(data.continuous_monitoring) : undefined}
                isLoading={isLoading}
                sortBy={sortBy}
                sortOrder={sortOrder}
                onSort={handleSort}
                filterCodes={filterCodes}
                onFilterChange={setFilterCodes}
                getStockType={() => "monitoring"}
                watchHook={watchHook}
                emptyState={{
                  icon: Eye,
                  title: "暂无重点关注股票",
                  description: "系统暂未推荐重点关注的股票，请稍后刷新查看。",
                  actionText: "刷新数据",
                  onAction: handleRefresh
                }}
                skeletonCount={6}
              />
            </TabsContent>
          </Tabs>
        </main>
      </div>
    </AuthGuard>
  )
}
